// components/removeList/removeList.js
const db = wx.cloud.database()
const app = getApp()
const _ = db.command
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    messageId: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    userMessage: {}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleDelMessage() {
      wx.showModal({
        title: "提示",
        content: "是否删除消息",
        confirmText: "删除",
        success: (res) => {
          if (res.confirm) {
            this.removeMessage()
          } else if (res.cancel) {}
        }
      })
    },
    handleAddFriend() {
      wx.showModal({
        title: "提示",
        content: "好友申请",
        confirmText: "同意",
        success: (res) => {
          if (res.confirm) {
            db.collection('users').doc(app.userInfo._id).update({
              data: {
                friendList: _.unshift(this.data.messageId)
              }
            }).then(res => {
              wx.cloud.callFunction({
                name: "update",
                data: {
                  collection: "users",
                  doc: this.data.messageId,
                  data: `{friendList: _.unshift('${app.userInfo._id}')}`
                }
              }).then(() => {
                this.removeMessage()
                wx.showToast({
                  title: '添加成功',
                })
              })
            })
          } else if (res.cancel) {}

        }
      })
    },
    removeMessage() {
      db.collection("message").where({
        userId: app.userInfo._id
      }).get().then(res => {
        let list = res.data[0].list
        list = list.filter((item) => {
          return item != this.data.messageId
        })
        //更新
        wx.cloud.callFunction({
          name: "update",
          data: {
            collection: "message",
            where: {
              userId: app.userInfo._id
            },
            data: {
              list
            }
          }
        }).then(() => {
          this.triggerEvent('myevent', list)
        })

      })


    }
  },
  lifetimes: {
    attached: function () {
      db.collection('users').doc(this.data.messageId).field({
        userPhoto: true,
        nickName: true
      }).get().then(res => {
        this.setData({
          userMessage: res.data
        })

      })
    },
  }
})